import { RouteRecordRaw } from 'vue-router';
import pinia from '/@/stores/index';
// import { useUserInfo } from '/@/stores/userInfo';
import { useRequestOldRoutes } from '/@/stores/requestOldRoutes';
import { Session } from '/@/utils/storage';
import { NextLoading } from '/@/utils/loading';
import { dynamicRoutes, notFoundAndNoPower } from '/@/router/route';
import { formatTwoStageRoutes, formatFlatteningRoutes, router } from '/@/router/index';
import { useRoutesList } from '/@/stores/routesList';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';

import { getAPI } from '/@/utils/axios-utils';
import { SysMenuApi } from '/@/api-services/api';
import { ElMessage } from 'element-plus';

import { getUserInfo } from '/@/api/user';
import { useThemeConfig } from '/@/stores/themeConfig';
import cache from '/@/utils/hook/cache';
// import { menuArr } from '/@/utils/test_menu.js'
// import { menuArr } from '/@/utils/011.ts';
import qs from 'qs';

// 权限按钮
import usePermission from '/@/stores/permissions';

const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');

// 后端控制路由

/**
 * 获取目录下的 .vue、.tsx 全部文件
 * @method import.meta.glob
 * @link 参考：https://cn.vitejs.dev/guide/features.html#json
 */
const dynamicViewsModules: Record<string, Function> = Object.assign({}, { ...layouModules }, { ...viewsModules });
// console.log(layouModules)
// console.log(888)
// console.log(dynamicViewsModules)

/**
 * 后端控制路由：初始化方法，防止刷新时路由丢失
 * @method NextLoading 界面 loading 动画开始执行
 * @method useUserInfo().setUserInfos() 触发初始化用户信息 pinia
 * @method useRequestOldRoutes().setRequestOldRoutes() 存储接口原始路由（未处理component），根据需求选择使用
 * @method setAddRoute 添加动态路由
 * @method setFilterMenuAndCacheTagsViewRoutes 设置路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
 */
export async function initBackEndControlRoutes() {
	// 界面 loading 动画开始执行
	if (window.nextLoading === undefined) NextLoading.start();
	// 无 token 停止执行下一步
	if (!Session.get('token')) return false;
	const storeThenmeConfig = useThemeConfig();
	let resData = null;
	// 子应用模式
	if (storeThenmeConfig.isMicro) {
		resData = cache.getCache('userInfoData');
	} else {
		// 独立模式 触发初始化用户信息 pinia
		let res = await getUserInfo();
		resData = res?.data;
	}

	let permissionStore = usePermission();
	// 保存permission按钮
	permissionStore.permissions = (resData && resData.permissions && resData.permissions) || ([] as string[]);

	// 获取路由菜单数据
	// const res = await getBackEndControlRoutes();
	const res = makeRoutes(resData?.apps, resData?.menus.concat(resData?.scadaScreenMenus));
	// const res = menuArr

	// 存储接口原始路由（未处理component），根据需求选择使用
	useRequestOldRoutes().setRequestOldRoutes(JSON.parse(JSON.stringify(res)));
	// 处理路由（component），替换 dynamicRoutes（/@/router/route）第一个顶级 children 的路由
	dynamicRoutes[0].children = await backEndComponent(res);
	// console.log(dynamicRoutes)

	// 添加动态路由
	await setAddRoute();
	// 设置路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
	await setFilterMenuAndCacheTagsViewRoutes();
	//账号路由配置(菜单权限)为空,返回登录页
	if (res.length == 0) {
		Session.clear();
	}
}

/**
 * 设置路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
 * @description 用于左侧菜单、横向菜单的显示
 * @description 用于 tagsView、菜单搜索中：未过滤隐藏的(isHide)
 */
export function setFilterMenuAndCacheTagsViewRoutes() {
	const storesRoutesList = useRoutesList(pinia);
	storesRoutesList.setRoutesList(dynamicRoutes[0].children as any);
	setCacheTagsViewRoutes();
}

/**
 * 缓存多级嵌套数组处理后的一维数组
 * @description 用于 tagsView、菜单搜索中：未过滤隐藏的(isHide)
 */
export function setCacheTagsViewRoutes() {
	const storesTagsView = useTagsViewRoutes(pinia);
	storesTagsView.setTagsViewRoutes(formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children);
}

/**
 * 处理路由格式及添加捕获所有路由或 404 Not found 路由
 * @description 替换 dynamicRoutes（/@/router/route）第一个顶级 children 的路由
 * @returns 返回替换后的路由数组
 */
export function setFilterRouteEnd() {
	let filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
	// notFoundAndNoPower 防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
	// 关联问题 No match found for location with path 'xxx'
	filterRouteEnd[0].children = [...filterRouteEnd[0].children, ...notFoundAndNoPower];
	return filterRouteEnd;
}

/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes（/@/router/route）第一个顶级 children 的路由一维数组，非多级嵌套
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 */
export async function setAddRoute() {
	await setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
		router.addRoute(route);
	});
}

/**
 * 请求后端路由菜单接口
 * @description isRequestRoutes 为 true，则开启后端控制路由
 * @returns 返回后端路由菜单数据
 */
export async function getBackEndControlRoutes() {
	var res = await getAPI(SysMenuApi).loginMenuGet();
	if (res.data.result == undefined || res.data.result.length < 1) {
		ElMessage.error('没有任何菜单权限，请联系管理员！');
		setTimeout(() => {
			Session.removeToken();
			window.location.reload();
		}, 3000);
	}
	return res.data.result;
}

/**
 * 重新请求后端路由菜单接口
 * @description 用于菜单管理界面刷新菜单（未进行测试）
 * @description 路径：/src/views/system/menu/component/addMenu.vue
 */
export function setBackEndControlRefreshRoutes() {
	getBackEndControlRoutes();
}

/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export function backEndComponent(routes: any) {
	if (!routes) return;
	return routes.map((item: any) => {
		// console.log(item)
		// console.log(item)
		// if (item.component) item.component = dynamicImport(dynamicViewsModules, item.component as string);
		// if (item.component) {

		// 	item.component = dynamicImport(dynamicViewsModules, 'test/index');
		// }
		// if (item.children) {

		// 	backEndComponent(item.children);

		// }
		item.component = dynamicImport(dynamicViewsModules, item.component as string);
		item.children && backEndComponent(item.children);
		// console.log(item)
		return item;
	});
}

/**
 * 后端路由 component 转换函数
 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件
 * @param component 当前要处理项 component
 * @returns 返回处理成函数后的 component
 */
export function dynamicImport(dynamicViewsModules: Record<string, Function>, component: string) {
	const keys = Object.keys(dynamicViewsModules);
	// console.log(keys)
	const matchKeys = keys.filter((key) => {
		const k = key.replace(/..\/views|../, '');

		return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
	});

	if (matchKeys?.length === 1) {
		const matchKey = matchKeys[0];
		// console.log(matchKey)
		return dynamicViewsModules[matchKey];
	}
	// ../views/test/index.vue
	if (matchKeys?.length > 1) {
		return false;
	} else if (matchKeys?.length === 0) {
		return dynamicViewsModules['../views/error/404.vue'];
	}
}

const makeRoutes = (app: [], menu: object[]) => {
	let appArr: any[] = [];
	for (let i = 0; i < app.length; i++) {
		let item: commonObj = app[i];

		let newItem: commonObj = {
			name: item.name,
			id: item.id,
			pid: item.pid,
			// sort: item.sort,
			code: item.code,
			permission: null,
			path: '/' + item.code,
			// path: '',
			component: '/test/index.vue',
		};
		let newItemMeta: commonObj = {
			icon: item.icon || '',
			isAffix: false,
			isHide: false,
			isIframe: false,
			isKeepAlive: false,
			isLink: null,
			order: i + 1,
			remark: null,
			status: 1,
			title: item.name,
		};
		// console.log(newItemMeta)
		newItem.meta = newItemMeta;
		let arr: any[] = [];
		for (let j = 0; j < menu.length; j++) {
			let menuItem: commonObj = menu[j];
			let newMenuItem: commonObj = {
				application: menuItem.application,
				name: menuItem.name,
				id: menuItem.id,
				pid: menuItem.pid,
				// sort: item.sort,
				permission: null,
				path: menuItem.path,
				// component: '/test/index.vue',
				component: menuItem.component,
			};
			const { redirect, isScadaScreen } = menuItem;
			const { link, target, show } = menuItem.meta;
			const isIframe = link && !redirect;
			const isKeepAlive = true;
			const hostUrl = location.origin;
			const query = {
				pageCode: menuItem.scadaPageCode,
				pageType: menuItem.scadaPageType,
			};
			// const isLink = link ? import.meta.env.VITE_HOST_URL + '/' + link + '?' + qs.stringify(query) : null;
			let isLink: string | null | undefined = '';
			if (isIframe) {
				isLink = isScadaScreen == 1 ? hostUrl + link + '?' + qs.stringify(query) : link;
			}
			if (target) {
				// 外链
				isLink = hostUrl + link;
				newMenuItem.path = isLink;
			}
			let newMenuItemItemMeta: commonObj = {
				icon: menuItem.meta.icon,
				isAffix: menuItem.meta.isAffix,
				isHide: !show,
				isIframe: isIframe,
				isKeepAlive: isKeepAlive,
				isLink: isLink,
				remark: null,
				status: 1,
				title: menuItem.meta.title,
				tagsViewName: menuItem.meta.title,
			};
			newMenuItem.meta = newMenuItemItemMeta;

			if (item.code == newMenuItem.application) {
				arr.push(newMenuItem);
			}
		}
		newItem.children = arr;
		appArr.push(newItem);
	}

	let newList = [];
	for (let i = 0; i < appArr.length; i++) {
		let item = appArr[i];
		let newItem = { ...item };
		if (item.children && item.children.length) {
			newItem.children = makeTreeData(item.children);
		}
		newList.push(newItem);
	}

	return newList;
};

interface commonObj {
	[propsName: string]: any;
}

const makeTreeData = (list: []) => {
	let arr: any[] = [];
	let allChildId: any[] = [];
	let newArr = [];
	for (let i = 0; i < list.length; i++) {
		let item: any = list[i];
		let childArr = list.filter((v: any) => {
			return item.id == v.pid;
		});
		if (childArr.length) {
			item.children = childArr;
			item.children.forEach((v: any) => {
				allChildId.push(v.id);
			});
		}
		arr.push(item);
	}
	for (let i = 0; i < arr.length; i++) {
		let item: any = arr[i];
		if (!allChildId.includes(item.id)) {
			newArr.push(item);
		}
	}
	return newArr;
};
